package com.sniff.atp.controller;

import com.alibaba.fastjson2.JSONObject;
import com.sniff.atp.dto.ContentDTO;
import com.sniff.atp.dto.customer.CustomerDTO;
import com.sniff.atp.entity.ToolsInfo;
import com.sniff.atp.manager.ToolsInfoMananager;
import com.sniff.atp.response.SniffResponse;
import com.sniff.atp.service.login.ClientLoginService;
import com.sniff.atp.utils.*;
import io.swagger.annotations.*;
import jodd.util.StringUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;

@Api(value = "用户模块", tags = "用户模块")
@RestController
@RequestMapping("/user")
public class ClientLoginController {

    @Autowired
    private ClientLoginService clientLoginService;
    @Autowired
    private ToolsInfoMananager toolsInfoMananager;
    @ApiOperation("登录接口")
    @GetMapping("/test/clientLogin")
    public Object test() {
        ToolsInfo toolsInfo = toolsInfoMananager.selectOne(1L);
        toolsInfo.setCount(toolsInfo.getCount() + 1);
        toolsInfoMananager.updateOne(toolsInfo);
        return clientLoginService.login("test", "123456");
    }

    /**
     * 获取手机验证码
     */
    @ApiOperation("获取验证码")
    @GetMapping("/getCode")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "String",name = "customerMobile",value = "手机号/邮箱",required = true)})
    public Object getCode(String customerMobile){
        ToolsInfo toolsInfo = toolsInfoMananager.selectOne(32L);
        toolsInfo.setCount(toolsInfo.getCount() + 1);
        toolsInfoMananager.updateOne(toolsInfo);
        String smsContent = clientLoginService.getCode(customerMobile);
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("smsContent",smsContent);
        return Result.SuccessJSON(map);
    }

    /**
     * 注册账号
     */
    @ApiOperation("注册账号")
    @RequestMapping(value = "/signup", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiImplicitParams({@ApiImplicitParam(name = "param0", value = "username"),
            @ApiImplicitParam(name = "param1", value = "invitationCode"),
            @ApiImplicitParam(name = "param2", value = "countryPlaceCode")})
    public Result signUp(@RequestParam(value = "param0",required = false) String username,
                         @RequestParam(value = "param1",required = false) String invitationCode,
                         @RequestParam(value = "param2",required = false) String countryPlaceCode) {
        ToolsInfo toolsInfo = toolsInfoMananager.selectOne(25L);
        toolsInfo.setCount(toolsInfo.getCount() + 1);
        toolsInfoMananager.updateOne(toolsInfo);

        String signName = "";

        if(StringUtils.isNotEmpty(username)&&!StringUtils.startsWith(username, " ")&&!StringUtils.startsWith(username, "\"")) {
            signName = username;
        }else {
            signName = RandomStringUtils.random(3, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") + DateUtil.longString();
        }

        String result = clientLoginService.signUp(signName, invitationCode, countryPlaceCode);
        JSONObject jsonObject = JsonUtil.strToJSONObject(result);
        String uuid = jsonObject.getJSONObject("data").getString("uuid");

        String s = clientLoginService.systemSourceLogin(uuid);
        JSONObject jsonObject1 = JsonUtil.strToJSONObject(s);
        String token = jsonObject1.getJSONObject("data").getString("token");
        clientLoginService.shopAdd(token, signName+"D2CShopping");

        String login = clientLoginService.login(signName);

        String customerId = JsonUtil.extractString(login, "data.customerRespDTO.mainCustomerId");
        DBUtil.insertOrUpdate("USER-新用户去掉新手引导", new ContentDTO("customerId", customerId));

       // Map<String, String> resultMap = JsonUtil.parseJson2Map(result);
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("username",signName);
        map.put("password","test123456");
        map.put("customerId",customerId);
        return Result.SuccessJSON(map);
    }

    @ApiOperation("手机号注册")
    @RequestMapping(value="/mobileSignup", method = {RequestMethod.POST})
    @ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "手机号"),
                        @ApiImplicitParam(name = "countryPlaceCode", value = "站点"),
                        @ApiImplicitParam(name = "invitationCode", value = "邀请码")})
    public SniffResponse<Object> moblieSignup(@RequestParam(value = "mobile", required = false) String mobile,
                                              @RequestParam(value = "invitationCode", required = false) String invitationCode,
                                              @RequestParam(value = "countryPlaceCode", required = true) String countryPlaceCode){

        String mobilePhone = "";
        if (StringUtils.isNotEmpty(mobile)){
            mobilePhone = mobile;
        }else {
            mobilePhone = RandomUtil.numberString(11);
        }


        clientLoginService.code(mobilePhone, countryPlaceCode);
        String code = clientLoginService.getCode(mobilePhone);

        String result = clientLoginService.signUp(mobilePhone, code, countryPlaceCode, invitationCode);
        JSONObject jsonObject = JsonUtil.strToJSONObject(result);
        String uuid = jsonObject.getJSONObject("data").getString("uuid");

        String s = clientLoginService.systemSourceLogin(uuid);
        JSONObject jsonObject1 = JsonUtil.strToJSONObject(s);
        String token = jsonObject1.getJSONObject("data").getString("token");
        clientLoginService.shopAdd(token, mobilePhone+"D2CShopping");

//        clientLoginService.code(mobilePhone);
//        String loginCode = clientLoginService.getCode(mobilePhone);
        String login = clientLoginService.mobileLogin(mobilePhone, countryPlaceCode, "7890");
        String customerId = JsonUtil.extractString(login, "data.customerRespDTO.mainCustomerId");
        DBUtil.insertOrUpdate("USER-新用户去掉新手引导", new ContentDTO("customerId", customerId));



        JSONObject response = new JSONObject();
        response.put("mobile", mobilePhone);
        response.put("code", code);
        response.put("countryPlaceCode", countryPlaceCode);
        return SniffResponse.pass(response);
    };

    /**
     * 账号充值
     */
    @ApiOperation("账号充值")
    @PostMapping(value = "/rechange")
    @ApiImplicitParams({@ApiImplicitParam(name = "username", value = "username",paramType = "String"),
            @ApiImplicitParam(name = "customerShopId", value = "customerShopId",paramType = "String"),
            @ApiImplicitParam(name = "systemType", value = "systemType",paramType = "String"),
            @ApiImplicitParam(name = "mobile", value = "mobile",paramType = "String")})
    public Result rechange(@RequestParam(value = "username",required = false) String username,
                           @RequestParam(value = "customerShopId",required = false) String customerShopId ,
                           @RequestParam(value = "systemType",required = false) String systemType,
                           @RequestParam(value = "mobile",required = false) String mobile) {
        ToolsInfo toolsInfo = toolsInfoMananager.selectOne(26L);
        toolsInfo.setCount(toolsInfo.getCount() + 1);
        toolsInfoMananager.updateOne(toolsInfo);

        //系统
        if(StringUtil.isEmpty(systemType) ){
            return Result.Failure("系统为必输！！");
        }

        //用户名和店铺id不能同时为空
        if(StringUtil.isEmpty(username) && StringUtil.isEmpty(customerShopId) && StringUtil.isEmpty(mobile) ){
            return Result.Failure("用户名和店铺id或手机号不能同时为空！！");
        }
        CustomerDTO customerDTO = new CustomerDTO();
        customerDTO.setCustomerShopId(customerShopId);
        customerDTO.setSystemType(systemType);
        customerDTO.setLoginName(username);
        customerDTO.setCustomerMobile(mobile);

        //3是直营，1，2是代采
        if( "3".equals(systemType)){
            //查询客户的supercustomerId
            String superCutsomerId = clientLoginService.qrySuperCustomerInfo(customerDTO);
            if(superCutsomerId == null || StringUtils.isEmpty(superCutsomerId) || superCutsomerId == "null"){
                return Result.Failure("查询不到用户信息！！");
            }
            //通过客户id增加金额
            clientLoginService.addAvaliableAmount2D(superCutsomerId);
        }else{
            //查询客户的supercustomerId
            String customerId = clientLoginService.qryCustomerInfoMix(customerDTO);
            if(customerId == null || StringUtils.isEmpty(customerId) || customerId == "null"){
                return Result.Failure("查询不到用户信息！！");
            }
            //通过客户id增加金额
            clientLoginService.addAvaliableAmount(customerId);
        }

        return Result.Success("充值成功");
    }

    /**
     * 账号类型
     */
    @RequestMapping(value = "/accountType", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result accountType(HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("1", "D2C");
        map.put("2", "B2B");
        return Result.Success(map);
    }

    /**
     * 修改会员等级
     */
    @ApiOperation("修改会员等级")
    @RequestMapping(value = "/changeMembershipLvl", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({@ApiImplicitParam(name = "param0", value = "membershipTemplateId"),
            @ApiImplicitParam(name = "param1", value = "username"),
            @ApiImplicitParam(name = "param2", value = "customerShopId")})
    public Result changeMembershipLvl(@RequestParam(value = "param0",required = false) String membershipTemplateId,
                                      @RequestParam(value = "param1",required = false) String username,
                                      @RequestParam(value = "param2",required = false) String customerShopId) {
        ToolsInfo toolsInfo = toolsInfoMananager.selectOne(27L);
        toolsInfo.setCount(toolsInfo.getCount() + 1);
        toolsInfoMananager.updateOne(toolsInfo);
        //用户名和店铺id不能同时为空
        if(StringUtil.isEmpty(username) && StringUtil.isEmpty(customerShopId) ){
            return Result.Failure("用户名和店铺id不能同时为空！！");
        }
        if(membershipTemplateId == null || StringUtil.isEmpty(membershipTemplateId) || membershipTemplateId == ""){
            //为空时默认为非会员
            membershipTemplateId = "1529379248047333378";
        }
        //获取用户的supercustomerid
        String systemType = "1";
        String superCustomerId = clientLoginService.qryCustomerInfoSupercustomerId(username,customerShopId,systemType);

        if(superCustomerId == null || StringUtils.isEmpty(superCustomerId) || superCustomerId == "null"){
            return Result.Failure("查询不到用户信息！！");
        }
        //通过客户id增加金额
        clientLoginService.changeMembershipLvl(superCustomerId,membershipTemplateId);
        return Result.Success("执行成功");
    }

}
